package com.qdlc.p2p.dal.dao.impl;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.Query;

import org.springframework.stereotype.Repository;

import com.qdlc.p2p.common.constant.Global;
import com.qdlc.p2p.common.util.StringUtil;
import com.qdlc.p2p.dal.common.dao.jpa.BaseDaoImpl;
import com.qdlc.p2p.dal.common.model.jpa.OrderFilter;
import com.qdlc.p2p.dal.common.model.jpa.PageDataList;
import com.qdlc.p2p.dal.common.model.jpa.QueryParam;
import com.qdlc.p2p.dal.common.model.jpa.SearchFilter;
import com.qdlc.p2p.dal.dao.AdditionalUserDrawLotteryDao;
import com.qdlc.p2p.dal.dto.AdditionalDrawLotteryRule;
import com.qdlc.p2p.dal.dto.AdditionalUserDrawLottery;
import com.qdlc.p2p.dal.dto.User;
import com.qdlc.p2p.dal.model.AdditionalUserDrawLotteryModel;

/**
 * Created by liaoxiangkai on 2015/11/12.
 */
@Repository("additionalUserDrawLotteryDao")
public class AdditionalUserDrawLotteryDaoImpl extends BaseDaoImpl<AdditionalUserDrawLottery> implements AdditionalUserDrawLotteryDao {

    public AdditionalUserDrawLottery getValidDrawLotteryByUserId(long userId) {
        StringBuilder sql = new StringBuilder();
        sql.append("SELECT ");
        sql.append("  * ");
        sql.append("FROM");
        sql.append("  " + Global.DB_PREFIX + "additional_user_draw_lottery");
        sql.append("  WHERE status = 0 ");
        sql.append("  AND count > 0 ");
        sql.append("  AND user_id = :user_id ");
        sql.append("  AND UNIX_TIMESTAMP(NOW()) >= UNIX_TIMESTAMP(start_time) ");
        sql.append("  AND UNIX_TIMESTAMP(NOW()) <= UNIX_TIMESTAMP(end_time)");
        sql.append("  ORDER BY add_time DESC");
        sql.append("  LIMIT 1");

        Query query = em.createNativeQuery(sql.toString(), AdditionalUserDrawLottery.class);
        query.setParameter("user_id", userId);
        List<AdditionalUserDrawLottery> list = query.getResultList();
        return null != list && list.size() > 0 ? list.get(0) : new AdditionalUserDrawLottery();
    }

    /**
     * 用户抽奖机会列表
     *
     * @param model
     * @return
     */
    @Override
    public PageDataList<AdditionalUserDrawLotteryModel> list(AdditionalUserDrawLotteryModel model) {
        QueryParam param = QueryParam.getInstance().addPage(model.getPage(), model.getRows());
        param.addOrder(OrderFilter.OrderType.DESC, "addTime");
        if (StringUtil.isNotBlank(model.getSearchName())) {
            SearchFilter orFilter1 = new SearchFilter("user.userName", SearchFilter.Operators.LIKE, model.getSearchName().trim());
            SearchFilter orFilter2 = new SearchFilter("user.realName", SearchFilter.Operators.LIKE, model.getSearchName().trim());
            param.addOrFilter(orFilter1, orFilter2);
        }else {
            //添加用户查询条件
            if (StringUtil.isNotBlank(model.getRealName())) {
                SearchFilter orFilter1 = new SearchFilter("user.userName", SearchFilter.Operators.LIKE, model.getRealName().trim());
                SearchFilter orFilter2 = new SearchFilter("user.realName", SearchFilter.Operators.LIKE, model.getRealName().trim());
                param.addOrFilter(orFilter1, orFilter2);
            }
            //添加规则查询条件
            if (StringUtil.isNotBlank(model.getRuleName())) {
                param.addParam("additionalDrawLotteryRule.name", SearchFilter.Operators.LIKE,  model.getRuleName());
            }
            //添加状态查询条件
            if (model.getStatus() != 99) {
                param.addParam("status", model.getStatus());
            }

        }
        param.addPage(model.getPage(), model.getRows());
        PageDataList<AdditionalUserDrawLottery> dataList = this.findPageList(param);
        PageDataList<AdditionalUserDrawLotteryModel> modelDataList = new PageDataList<AdditionalUserDrawLotteryModel>();
        List<AdditionalUserDrawLotteryModel> list = new ArrayList<AdditionalUserDrawLotteryModel>();
        if (dataList.getList() != null && dataList.getList().size() > 0) {
            for (AdditionalUserDrawLottery entity : dataList.getList()) {
                AdditionalUserDrawLotteryModel additionalUserDrawLotteryModel = AdditionalUserDrawLotteryModel.instance(entity);
                //将规则名设置给model
                AdditionalDrawLotteryRule drawLotteryRule = entity.getAdditionalDrawLotteryRule();
                if (null != drawLotteryRule && StringUtil.isNotBlank(drawLotteryRule.getName()))
                    additionalUserDrawLotteryModel.setRuleName(drawLotteryRule.getName());
                //把用户名设置给model
                User user = entity.getUser();
                if (null != user) {
                    additionalUserDrawLotteryModel.setUserName(user.getUserName());
                    if (StringUtil.isNotBlank(user.getRealName())) {
                        additionalUserDrawLotteryModel.setRealName(user.getRealName());
                    }
                }
                list.add(additionalUserDrawLotteryModel);
            }
        }
        modelDataList.setPage(dataList.getPage());
        modelDataList.setList(list);
        return modelDataList;
    }

    /**
     * 将用户抽奖机会设置成无效
     *
     * @param status
     * @param userLotteryId
     * @return
     */
    @Override
    public int doInvalid(int status, long userLotteryId) {
        String jpql = "update AdditionalUserDrawLottery set status = ?1 where id = ?2";
        Query query = em.createQuery(jpql);
        query.setParameter(1, status);
        query.setParameter(2, userLotteryId);
        return query.executeUpdate();
    }


}
